$(function () {
    var queryUrl = '../devretreadrecord/list?type=1';
    var Id = getQueryString('Id');
    if(Id){
        queryUrl += '&Id=' + Id;
    }
    $("#jqGrid").Grid({
        url: queryUrl,
        colModel: [
            {label: '物料名称', name: 'materName', index: 'sp.name', width: 80},
            {label: '规格型号', name: 'materSpec', index: 'sp.spec', width: 120},
            {label: '物料编码', name: 'erpCode', index: 'ERP_CODE', width: 80},
            {label: '单位', name: 'materUnit', index: 'sp.unit', width: 30},
            {label: '数量', name: 'retNum', index: 'RET_NUM', width: 30},
            {label: '零件原值', name: 'origVal', index: 'ORIG_VAL', width: 60},
            {label: '维修成本', name: 'primeCost', index: 'PRIME_COST', width: 60},
            {label: '申报节约价值', name: 'lessCost', index: 'LESS_COST', width: 80},
            {label: '工厂核算价值', name: 'accCost', index: 'ACC_COST', width: 80},
            {label: '备件ID', name: 'proId', index: 'PRO_ID', width: 80, hidden: true},
            {
                label: '状态', name: 'isFixed', index: 'IS_FIXED', width: 45,
                formatter: function (value, col, row) {
                    return sysEnums.SP_SCARP_FIX_STATUS[row.isFixed];
                }
            },
            {label: '实施单位', name: 'expUnitName', index: 'EXP_UNIT_NAME', width: 70},
            {label: '归属单位', name: 'btUnitName', index: 'BT_UNIT_NAME', width: 70},
            {label: '维修人员名称', name: 'repairUserName', index: 'REPAIR_USER_NAME', width: 80},
            {label: '备注信息', name: 'remark', index: 'REMARK', width: 80},
            {label: '报废记录ID', name: 'scarpRecordId', index: 'SCARP_RECORD_ID',hidden: true},
            {
                label: '换件记录', name: 'devCode', index: 'DEV_CODE', width: 60,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.detail(\"" + escape(JSON.stringify(row)) + "\")'>&nbsp;详情</button>";
                }
            },
            {label: '完善记录ID', name: 'repairRecordId', index: 'REPAIR_RECORD_ID',hidden: true},
            {label: 'id', name: 'id', index: 'ID', key: true, hidden: true}]
    });
    vm.getSparePartUnit();
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        isShow:1,
        isEditing:true,
        showList: true,
        title: null,
        scarpRecordId:'',//报废记录id
        businessId:'',//维修工单id
        partUnitList: [], // 备件单位列表，用于新增或修改备件时单位的下拉选择
        devRetreadRecord: {
            id:'',
            spareId:'',
            matterCode : '',
            materName:'',
            materUnit:'',
            retNum:'',
            origVal :''
        },
        ruleValidate: {
            materName: [
                {required: true, message: '名称不能为空', trigger: 'change'}
            ]
        },
        q: {
            name: '',//备件名称
            spec:'',//备件规格
            partCode:'',//备件编码
            erpCode:'',//ERP编码
            producor:'',//生产厂商
            expUnit:'',//xx车间
            btUnit:'',//归属车间
            isFixed:'',//状态
            repairUserName:''//维修人员姓名
        },
        devKind:'1',//换件记录选择备件默认的值
        workshopList: [] ,// 所属车间下拉option列表
        annexFile:[],
        annexListShow:false,
        statusList: enumsToList('SP_SCARP_FIX_STATUS'),
    },
    created: function () {
        // 加载车间列表
        this.loadWorshopList();
    },
    methods: {
        loadWorshopList: function () {
            var _this = this;
            Ajax.request({
                url: '../sys/dept/listByDeptLevel?deptLevel=2',
                async: true,
                successCallback: data => {
                    this.workshopList = data.list;
                }
            });
        },
        // 查看工单详情
        orderDetails: function () {
            var data = getSelectedRowData("#jqGrid");
            if (vm.scarpRecordId == null || vm.scarpRecordId == '') {
                alert('手动新增记录，无关联工单信息！');
                return;
            }

            openWindow({
                type: 2,
                title: '<i class="fa fa-bars"></i> 维修工单详情',
                content: '../device/devmaintenworkview.html?Id=' + data.repairRecordId
            });
        },
        /**
         * 选择备件*/
        getSpareInfo: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择备件',
                content: '../spare/sparePartSelect.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getSparePart();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        //在这拉取近三年用量和库存信息
                        vm.devRetreadRecord.spareId = res.id;
                        vm.devRetreadRecord.matterCode = res.partCode;
                        vm.devRetreadRecord.materName = res.name;
                        vm.devRetreadRecord.materUnit = res.unit;
                        vm.devRetreadRecord.materSpec = res.spec;
                        vm.devRetreadRecord.retNum = res.safeNum;
                        vm.devRetreadRecord.origVal = res.price;
                        layer.close(index);

                    }
                }
            })
        },
        usageAndInventory(ids){
            Ajax.request({
                url: '../sparepart/getSparePartStat'+'?id='+ids,
                async: true,
                successCallback: function (data) {
                    vm.threeYearsInformation = data.statResult;
                }
            });
        },
        /*获取换件记录*/
        getChangeRecord:function () {
            var queryUrl = '../sparepartconsumrecord/list';
            var paramArray = [];
            if (vm.businessId) {
                paramArray.push('businessId=' + vm.businessId);
            }
            paramArray.push('type=' + 'SCARP_REPAIR');
            if (paramArray.length > 0) {
                queryUrl += '?' + paramArray.join('&');
            }
            $.jgrid && ($.jgrid.info_dialog = function (caption, content, c_b, modalopt) {
                alert(content);
            });
            $("#swapRecord").Grid({
                url: queryUrl,
                height: 110,
                colModel: [
                    {label: '备件编码', name: 'partCode', index: 'PART_CODE', width: 100},
                    {label: '备件名称', name: 'name', index: 'NAME', width: 100},
                    {label: '规格', name: 'spec', index: 'SPEC', width: 200},
                    {label: '添加人', name: 'createUserName', width: 60, sortable: false, hidden: true},
                    {label: '添加时间', name: 'gmtCreate', width: 60, sortable: false, hidden: true},
                    {label: '领料单号', name: 'materCode', width: 100, sortable: false},
                    {label: '使用数量', name: 'num', index: 'NUM',  editable: true, editrules: {number: true}},
                    {name: 'sparePartId', hidden: true},
                    {name: 'type', hidden: true},
                    {name: 'businessId', hidden: true},
                    {label: 'id', name: 'id', index: 'ID', key: true, hidden: true},
                ],
                forceFit: true,
                cellEdit: true,
                cellsubmit: 'remote',
                cellurl: '../sparepartconsumrecord/update',
                afterSubmitCell(serverresponse, rowid, cellname, value, iRow, iCol) {
                    vm.ChangeRecordReload();
                    if (serverresponse.responseJSON.code == 0) {
                        vm.ChangeRecordReload();
                        return [true,""];
                    } else {
                        return [false,serverresponse.responseJSON.msg];
                    }
                }
            });
        },
        /* 重新加载*/
        ChangeRecordReload: function (event) {
            // 清空postData缓存数据
            var postData = $("#swapRecord").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            var page = $("#swapRecord").jqGrid('getGridParam', 'page');
            // 构建查询参数
            var param = {};
            if (vm.businessId) {
                param.businessId = vm.businessId;
            }
            if (vm.type) {
                param.type = vm.type;
            }
            $("#swapRecord").jqGrid('setGridParam', {
                search: true,
                postData: param,
                page: page
            }).trigger("reloadGrid", [{page: 1}]);
        },
        //显示备件列表-物料编码
        getSparePart: function () {
            let _this = this;
            if (vm.devKind == '1') {
                // 生产设备 sparePartmaintenanceDetails
                openWindow({
                    type: 2,
                    title: '<i class="fa fa-file-text-o"></i> 选择备件',
                    // content: '../spare/sparePartQuery.html',
                    content: '../spare/sparePartmaintenanceDetails.html?materialType=2',
                    btn: ['确定', '取消'],
                    btn1: function (index) {
                        var iframeWin = window["layui-layer-iframe" + index];
                        var res = iframeWin.getSparePart();
                        console.log("显示备件信息",res)
                        if (res.actualNum - res.replaceNum < 0) {
                            alert('可用数据小于1');
                            return
                        }
                        vm.sparePartConsumRecord = {
                            num: 0,
                            materialRecordId: res.id, // 领料明细ID
                            sparePartId: res.spareId,
                            businessId: _this.businessId, // 维修记录ID
                            type:'SCARP_REPAIR',
                        };
                        layer.close(index);
                        Ajax.request({
                            url: "../sparepartconsumrecord/save",
                            params: JSON.stringify(vm.sparePartConsumRecord),
                            type: "POST",
                            contentType: "application/json",
                            successCallback: function (r) {
                                alert('操作成功', function (index) {
                                    vm.ChangeRecordReload();
                                });
                            }
                        });
                    }
                })
            } else if (vm.devKind == '2') {
                // 能源设备从备件库存中选择
                openWindow({
                    type: 2,
                    title: '<i class="fa fa-file-text-o"></i> 选择备件',
                    content: '../spare/sparestock_choose.html',
                    btn: ['确定', '取消'],
                    btn1: function (index) {
                        var iframeWin = window["layui-layer-iframe" + index];
                        var res = iframeWin.getSpareStroe();
                        if (!res) {
                            iview.Message.error("请选择一条记录");
                        } else {
                            let storeNum = parseInt(res.storeNum);
                            if (storeNum == 0 || (storeNum - parseInt(res.locNum) <= 0)) {
                                alert("可用库存不足，请更换!");
                                return;
                            }
                            vm.sparePartConsumRecord = {
                                num: 0,
                                sparePartId: res.spareId,
                                businessId: _this.businessId,
                                type: _this.type,
                                posId: res.id
                            };
                            layer.close(index);
                            Ajax.request({
                                url: "../sparepartconsumrecord/save",
                                params: JSON.stringify(vm.sparePartConsumRecord),
                                type: "POST",
                                contentType: "application/json",
                                successCallback: function (r) {
                                    alert('操作成功', function (index) {
                                        vm.ChangeRecordReload();
                                    });
                                }
                            });
                        }
                    }
                })
            }
        },
        /*换件记录删除*/
        del: function (event) {
            let ids = getSelectedRows("#swapRecord");
            if (ids == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../sparepartconsumrecord/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.ChangeRecordReload();
                        });
                    }
                });
            });
        },
        getSparePartUnit: function(){
            // 获取备件单位
            Ajax.request({
                url: '../sparepart/listUnit',
                async: false,
                successCallback: function (r) {
                    vm.partUnitList = r.sparePartUnits;
                }
            });
        },
        //换件详情
        detail: function (res) {
            var postData = $("#swapRecords").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            let data = JSON.parse(unescape(res))

            vm.businessId = data.id
            vm.getChangeRecordDetail();
            vm.ChangeRecordDetail();
            layer.open({
                type: 1,
                title: "换件记录",
                closeBtn: 0,
                area: ['700px', 'auto'],
                offset: '10vh',
                shadeClose: true,
                skin: 'yourclass',
                content: $('#auditHistoryArea'),
            });
        },
        getChangeRecordDetail:function () {
            var queryUrl = '../sparepartconsumrecord/list';
            var paramArray = [];
            if (vm.businessId) {
                paramArray.push('businessId=' + vm.businessId);
            }
            paramArray.push('type=' + 'SCARP_REPAIR');
            if (paramArray.length > 0) {
                queryUrl += '?' + paramArray.join('&');
            }
            $.jgrid && ($.jgrid.info_dialog = function (caption, content, c_b, modalopt) {
                alert(content);
            });
            $("#swapRecordDetail").Grid({
                url: queryUrl,
                height: 110,
                colModel: [
                    {label: '备件编码', name: 'partCode', index: 'PART_CODE', width: 100},
                    {label: '备件名称', name: 'name', index: 'NAME', width: 100},
                    {label: '规格', name: 'spec', index: 'SPEC', width: 200},
                    {label: '添加人', name: 'createUserName', width: 60, sortable: false, hidden: true},
                    {label: '添加时间', name: 'gmtCreate', width: 60, sortable: false, hidden: true},
                    {label: '领料单号', name: 'materCode', width: 100, sortable: false},
                    {label: '使用数量', name: 'num', index: 'NUM', width: 120, editable: true, editrules: {number: true}},
                    {name: 'sparePartId', hidden: true},
                    {name: 'type', hidden: true},
                    {name: 'businessId', hidden: true},
                    {label: 'id', name: 'id', index: 'ID', key: true, hidden: true},
                ],
            });
        },
        ChangeRecordDetail: function (event) {
            // 清空postData缓存数据
            /*debugger
            var postData = $("#swapRecordDetail").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });*/
            var page = $("#swapRecordDetail").jqGrid('getGridParam', 'page');
            // 构建查询参数
            var param = {};
            if (vm.businessId) {
                param.businessId = vm.businessId;
            }
            param.type = 'SCARP_REPAIR';
            $("#swapRecordDetail").jqGrid('setGridParam', {
                // search: true,
                postData: param,
                page: page
            }).trigger("reloadGrid", [{page: 1}]);
        },
        //审核详情
        shviewOption: function (res) {
            let data = JSON.parse(unescape(res))
            if (!data.approvalName) {
                data.approvalName = "-"
            }
            let dom = "<div class='details' >" +
                "<table>" +
                "<tr><td>审核人：</td><td>" + data.approvalName + "</td></tr>" +
                "<tr><td>审核状态：</td><td>" + sysEnums.CHECK_FLAG[data.approvalStatus] + "</td></tr>" +
                "<tr><td>审核时间：</td><td>" + transDate(data.approvalTime, "yyyy-MM-dd hh:mm") + "</td></tr>" +
                "<tr><td>创建时间：</td><td>" + transDate(data.createDate, "yyyy-MM-dd hh:mm") + "</td></tr>" +
                "</table></div>"
            layer.open({
                type: 1,
                title: "详情",
                closeBtn: 0,
                area: ['450px'],
                offset: '10vh',
                shadeClose: true,
                skin: 'yourclass',
                content: dom
            });
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.isShow = '0';
            vm.isEditing = false;
            vm.showList = false;
            vm.title = "新增";
            vm.devRetreadRecord = {
                materSpec:'',
                spareId:'',
                matterCode : '',
                materName:'',
                materUnit:'',
                retNum:'',
                origVal :'',
                'type': 1
            };

        },
        /**
         * 完善维修记录
         */
        update: function (event) {

            var id = getSelectedRow("#jqGrid");
            var record = getSelectedRowData("#jqGrid");
            console.log("record",record)
            if (id == null) {
                return;
            }
            vm.isShow = '1';
            vm.isEditing = true;
            vm.showList = false;
            vm.title = "完善维修记录";
            vm.businessId = id
            vm.scarpRecordId =record.scarpRecordId
            vm.getInfo(id);
        },
        saveOrUpdate: function (event) {
            var url = vm.devRetreadRecord.id == null ? "../devretreadrecord/save" : "../devretreadrecord/update";
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.devRetreadRecord),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.devRetreadRecord = {'delFlag': 0, 'id': id};
            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../devretreadrecord/updateDel",
                    params: JSON.stringify(vm.devRetreadRecord),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../devretreadrecord/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.devRetreadRecord = r.devRetreadRecord;
                    /*加载换件记录*/
                    vm.getChangeRecord()
                    vm.getAnnexList()
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    'name': vm.q.name,
                    'spec': vm.q.spec,
                    'partCode': vm.q.partCode,
                    'erpCode': vm.q.erpCode,
                    'producor': vm.q.producor,
                    'expUnit': vm.q.expUnit,
                    'btUnit': vm.q.btUnit,
                    'isFixed':vm.q.isFixed,
                    'repairUserName': vm.q.repairUserName
                },
                page: page
            }).trigger("reloadGrid",[{page: 1}]);
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            vm.q = {
                name: '',//备件名称
                spec:'',//备件规格
                partCode:'',//备件编码
                erpCode:'',//ERP编码
                producor:'',//生产厂商
                expUnit:'',//xx车间
                btUnit:'',//xx车间
                isFixed:'',//状态
                repairUserName:''//维修人员姓名
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            vm.isShow = '1';
            vm.devRetreadRecord.isFixed = vm.devRetreadRecord.isFixed || 0;
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        /*获取附件列表*/
        getAnnexList:function (){
            var queryUrl = '../annexfile/equList';
            var paramArray = [];
            if (vm.businessId) {
                paramArray.push('moduleId=' + vm.businessId);
            }
            paramArray.push('moduleType=' + '3');
            if (paramArray.length > 0) {
                queryUrl += '?' + paramArray.join('&');
            }
            $("#annexList").Grid({
                url: queryUrl,
                height: 150,
                colModel: [
                    {label: '附件标题', name: 'fileName', index: 'FILE_NAME', width: 120},
                    {label: '附件名称', name: 'relName', index: 'REL_NAME', width: 160},
                    {
                        label: '上传时间', name: 'uploadDate', index: 'UPLOAD_DATE', width: 160, formatter: function (value) {
                            return transDate(value, "yyyy-MM-dd hh:mm:ss");
                        }
                    },
                    {label: '上传用户', name: 'createUserName', index: 'CREATE_NAME', width: 120},
                    {
                        label: '操作', width: 60, align: 'center', sortable: false,
                        formatter: function (value, col, row) {
                            return "<div onclick='fileCommonHandle(\"" + row.url + "\", \"" + row.relName + "\")'><i class='fa fa-eye'></i>&nbsp;查看</div>"
                        }
                    },
                    {label: 'id', name: 'id', index: 'ID', key: true, hidden: true}
                ]
            });
        },
        /*附件modal 打开*/
        annexModalShow(){
            vm.annexListShow = true;
            vm.annexFile = {
                id: '',
                moduleType: '1',
                moduleId: vm.businessId,
                relName: '',
                fileName: '',
                url: ''
            };
        },
        /*确认上传*/
        annexSubmit:function (){
            var url = '../annexfile/saveDevEqu';
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.annexFile),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.annexListReload()
                        vm.annexListShow = false;
                    });
                }
            });
        },
        /*取消*/
        annexCancel(){
            vm.annexListShow = false;
            vm.annexFile = {
                id: '',
                moduleType: '',
                moduleId: '',
                relName: '',
                fileName: '',
                url: ''
            }
        },
        annexListReload:function (){
            // 清空postData缓存数据
            var postData = $("#annexList").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            var page = $("#annexList").jqGrid('getGridParam', 'page');
            // 构建查询参数
            var param = {};
            if (vm.businessId) {
                param.moduleId = vm.businessId;
            }
            if (vm.type) {
                param.moduleType ='3';
            }
            $("#annexList").jqGrid('setGridParam', {
                search: true,
                postData: param,
                page: page
            }).trigger("reloadGrid", [{page: 1}]);
        },
        /*附件删除*/
        delAnnexList:function (){
            var ids = getSelectedRows("#annexList");
            if (ids == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../annexfile/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.annexListReload();
                        });
                    }
                });
            });
        },
        handleBeforeUpload: function(){
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleSuccess: function (res, file) {
            if(res.code == 0){
                this.$Loading.finish();
                iview.Message.success('文件上传成功!');
                vm.annexFile.url = res.url;
                vm.annexFile.fileName = res.fileName;
                vm.annexFile.relName = res.name;
            }else{
                this.$Loading.error();
                iview.Message.error('文件上传失败!');
            }
        },
        handleMaxSize: function (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
            });
        },

    }
});
